import { Component, OnInit, OnDestroy } from '@angular/core';
import { CommonService } from '../../core/services/common.service';
import { ToolService } from '../../core/services/tool.service';
import { MapService, StyleService } from '../../core';
@Component({
  selector: 'app-question-manage',
  templateUrl: './question-manage.component.html',
  styleUrls: ['./question-manage.component.scss']
})
export class QuestionManageComponent implements OnInit, OnDestroy {
  listData = null;
  pagenNo = 1;
  totalRecord = 0;
  keyword = '';
  subscriptations = [];
  mapboxglmap = null;
  constructor(
    private toolService: ToolService,
    private apboxMapService: MapService,
    private styleMapService: StyleService,
    private commonService: CommonService
  ) { }

  ngOnInit() {
    this.apboxMapService.init().then((mapboxglmap: any) => {
      this.mapboxglmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded() || this.apboxMapService.styleLoaded) {
        // this.mapInit();
      } else {
        mapboxglmap.on('load', () => {
          //   this.mapInit();
        });
      }
    });
    // 没做请求之前进行列表数据获取！
    this.subscriptations.push(
      postal.channel('QUESTION_TREE_CHANNEL').subscribe('refrese', res => {
        // 列表数据刷新！
        this.getListData(this.getParams());
        this.commonService.getQuestionGeojson();
      }),
    );
    this.getListData(this.getParams());
  }
  search() {
    this.pagenNo = 1;
    this.toolService.throttle(this.getListData(this.getParams()), 2000);
  }
  updateList(e) {
    this.getListData(this.getParams());
  }
  getListData(params) {
    this.commonService.getListData(params).subscribe(res => {
      if (res.code === 1 && res.data) {
        this.listData = res.data.list.features;
        this.totalRecord = res.data.totalRecord;
        // 点，线，面绘制
        this.drawPageGeo(this.listData);
      } else {
        this.listData = null;
        this.totalRecord = 0;
      }
    });
  }
  // 分页绘制
  drawPageGeo(listData) {
  }
  pageIndexChange() {
    this.getListData(this.getParams());
  }
  getParams() {
    return {
      keyword: this.keyword || '',
      pageSize: 13,
      pageNo: this.pagenNo
    };
  }
  // 选中列表项 定位
  searchListItemClick(item) {
    const { type, coordinates } = item.geometry;
    switch (type) {
      case 'Point':
        this.mapboxglmap.flyTo({
          center: coordinates,
          zoom: 18,
        });
        break;
      case 'LineString':
        this.styleMapService.fitLineBounds(this.mapboxglmap, coordinates);
        break;
      case 'Polygon':
        this.styleMapService.fitPolygonBoundingBox(this.mapboxglmap, coordinates);
        break;
      default:
        break;
    }
  }
  ngOnDestroy() {
    // 取消订阅
    this.subscriptations.forEach(element => {
      element.unsubscribe();
    });
  }
}
